import sys
from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
from transfer.config import get_config


class Session:

    def __init__(self):
        # {
        # 'useid': {'time':time, 'tokens':"kkkk", 'data':{}}
        # }
        self.info = {}
        self.check_func = None

    def __check(self):
        if callable(self.check_func):
            self.check_func()

    def register_check_function(self, func):
        if callable(func):
            self.check_func = func
        else:
            print('ERR: check_function must be callable!')


class RequestHandler(SimpleXMLRPCRequestHandler):
    session = Session()

    def do_POST(self):

        super(RequestHandler, self).do_POST()


class Server:

    def __init__(self):
        self.ip, self.port = get_config('server')
        self.server = SimpleXMLRPCServer((self.ip, self.port),
                                         allow_none=True, use_builtin_types=True)
        self.server.register_introspection_functions()
        self.server.register_multicall_functions()
        # system.listMethods, system.methodHelp and system.methodSignature
        # self.enable_login = True

    def start(self):
        try:
            print('服务端运行中，使用Ctrl+C退出。')
            self.server.serve_forever()
        except KeyboardInterrupt as e:
            print('用户请求退出服务，系统退出!')
            self.stop()
            sys.exit(0)

    def stop(self):
        self.server.shutdown()

    def register_function(self, func, name=None):
        """
        注册一个函数，如：
        @server.register_function
        def add(a, b):
            return a + b
        :param func:
        :param name: 别名
        :return: 无
        """
        self.server.register_function(func, name)

    def register_instance(self, instance, allow_dotted_names=True):
        """
        注册一个实例
        :param allow_dotted_names:
        :param instance:某个类的实例
        :return:
        """
        self.server.register_instance(instance, allow_dotted_names)


server = Server()